import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface Dish {
  id: number
  name: string
  price: number
  description: string
  image: string
}

export interface CartItem extends Dish {
  quantity: number
}

export const useCartStore = defineStore('cart', () => {
  // 购物车商品列表
  const items = ref<CartItem[]>([])

  // 计算属性：购物车总数量
  const totalCount = computed(() => {
    return items.value.reduce((sum, item) => sum + item.quantity, 0)
  })

  // 计算属性：购物车总价格
  const totalPrice = computed(() => {
    return items.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
  })

  // 添加商品到购物车
  const addItem = (dish: Dish) => {
    const existingItem = items.value.find(item => item.id === dish.id)
    
    if (existingItem) {
      // 如果商品已存在，增加数量
      existingItem.quantity++
    } else {
      // 如果商品不存在，添加新商品
      items.value.push({
        ...dish,
        quantity: 1
      })
    }
    
    // 保存到本地存储
    saveToLocalStorage()
  }

  // 从购物车移除商品
  const removeItem = (dishId: number) => {
    const index = items.value.findIndex(item => item.id === dishId)
    if (index > -1) {
      items.value.splice(index, 1)
      saveToLocalStorage()
    }
  }

  // 更新商品数量
  const updateQuantity = (dishId: number, quantity: number) => {
    const item = items.value.find(item => item.id === dishId)
    if (item) {
      if (quantity > 0) {
        item.quantity = quantity
      } else {
        // 如果数量为0或负数，从购物车移除
        removeItem(dishId)
      }
      saveToLocalStorage()
    }
  }

  // 清空购物车
  const clearCart = () => {
    items.value = []
    saveToLocalStorage()
  }

  // 保存到本地存储
  const saveToLocalStorage = () => {
    localStorage.setItem('cart-items', JSON.stringify(items.value))
  }

  // 从本地存储加载
  const loadFromLocalStorage = () => {
    const savedItems = localStorage.getItem('cart-items')
    if (savedItems) {
      items.value = JSON.parse(savedItems)
    }
  }

  // 初始化时加载本地存储的数据
  loadFromLocalStorage()

  return {
    items,
    totalCount,
    totalPrice,
    addItem,
    removeItem,
    updateQuantity,
    clearCart
  }
})